package com.wayne.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.cj.util.StringUtils;
import com.wayne.binding.MapperRegistry;
import com.wayne.io.Resources;
import com.wayne.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
  /**
   * 该方法就是对配置文件进行解析，封装Configuration对象
   *
   * @param inputStream
   * @return
   */
  public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
    Document document = new SAXReader().read(inputStream);
    Element rootElement = document.getRootElement();
    // 解析datasource属性
    List<Element> propertyList = rootElement.selectNodes("//property");
    Properties properties = new Properties();
    propertyList.stream().forEach(property -> properties.put(property.attributeValue("name"), property.attributeValue("value")));
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
    comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
    comboPooledDataSource.setUser(properties.getProperty("username"));
    comboPooledDataSource.setPassword(properties.getProperty("password"));
    Configuration configuration = new Configuration();
    configuration.setDataSource(comboPooledDataSource);
    // mapper.xml 解析： 拿到路径---字节输入流---dom4j进行解析
    List<Element> mapperList = rootElement.selectNodes("//mapper");
    mapperList.stream().forEach(mapper -> {
      String source = mapper.attributeValue("source");
      String packageName = mapper.attributeValue("package");
      if(!StringUtils.isNullOrEmpty(source)) {
        InputStream mapperStream = Resources.getResourceAsStream(source);
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        xmlMapperBuilder.parse(mapperStream);
      } else if(!StringUtils.isNullOrEmpty(packageName)) {
        configuration.getMapperRegistry().addMappers(packageName);
      }
    });
    return configuration;
  }
}
